package pl.un4giv3n.mightvsmagic.action;

import javax.persistence.EntityManager;

import pl.un4giv3n.mightvsmagic.entity.ActivityType;
import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.entity.UserActivity;
import pl.un4giv3n.mightvsmagic.utils.ActivityLogUtil;
import pl.un4giv3n.mightvsmagic.utils.UserUtil;

/**
 * @author andrzejewskia 
 * change user password
 */
public class ChangeLoginAction extends ProfilePageAction {

	private static final long serialVersionUID = 1L;

	/**
	 * new login
	 */
	private String newLogin = "";
	/**
	 * user passwd
	 */
	private String password = "";

	/**
	 * logged in user
	 */
	private User user;

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.un4giv3n.mightvsmagic.action.PersistenceAction#execute()
	 */
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if(user == null){
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		password = UserUtil.encyptPassword(password.trim());
		if (validateData(entityManager)) {
			entityManager.getTransaction().begin();
			user.setLogin(newLogin);
			entityManager.merge(user);
			UserActivity activity = ActivityLogUtil.createActivity(ActivityType.CHANGE_LOGIN, user.getId(),"Zmiana loginu na " + newLogin);
			entityManager.persist(activity);
			entityManager.flush();
			entityManager.getTransaction().commit();
			entityManager.close();
			return SUCCESS;
		} else {
			entityManager.close();
			return INPUT;
		}
	}

	/**
	 * @param entityManager 
	 * @param entityManager 
	 * @return true if password can be changed
	 */
	private boolean validateData(EntityManager entityManager) {
		boolean valid = true;
		if(!password.equals(user.getPassword())){
			valid = false;
			addActionError("Niepoprawne hasło");
		}
		if (!UserUtil.validateLogin(newLogin)) {
			valid = false;
			addActionError("Niepoprawny login. Dozwolne są znaki alfanumeryczne i _");
		} 
		if (!UserUtil.isLoginFree(newLogin, entityManager)) {
			valid = false;
			addActionError("Ten login jest już zajęty");
		}
		return valid;
	}

	public String getNewLogin() {
		return newLogin;
	}

	public void setNewLogin(String newLogin) {
		this.newLogin = newLogin;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}


}
